#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
探针代理服务
提供探针服务的启动和管理功能
"""

import os
import sys
from flask import Flask, request, jsonify
from probe_sdk.detector import DataComplianceDetector

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

app = Flask(__name__)

# 初始化检测器
# 从环境变量获取服务URL，如果没有则使用默认值
SERVICE_URL = os.environ.get('CDCRS_SERVICE_URL', 'http://go_service:8080')
detector = DataComplianceDetector(SERVICE_URL)


@app.route('/probe/detect', methods=['POST'])
def probe_detect():
    """
    探针敏感数据检测接口
    
    Returns:
        json: 检测结果
    """
    try:
        data = request.get_json()
        text = data.get('text', '')
        
        if not text:
            return jsonify({"error": "文本内容不能为空"}), 400
            
        result = detector.detect_sensitive_data(text)
        return jsonify(result)
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route('/probe/compliance', methods=['POST'])
def probe_compliance():
    """
    探针合规检查接口
    
    Returns:
        json: 合规检查结果
    """
    try:
        data = request.get_json()
        text = data.get('text', '')
        
        if not text:
            return jsonify({"error": "文本内容不能为空"}), 400
            
        result = detector.check_compliance(text)
        return jsonify(result)
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route('/probe/process', methods=['POST'])
def probe_process():
    """
    探针完整处理接口
    
    Returns:
        json: 完整处理结果
    """
    try:
        data = request.get_json()
        text = data.get('text', '')
        
        if not text:
            return jsonify({"error": "文本内容不能为空"}), 400
            
        result = detector.process_data(text)
        return jsonify(result)
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route('/probe/health', methods=['GET'])
def probe_health():
    """
    探针健康检查接口
    
    Returns:
        json: 健康状态
    """
    return jsonify({"status": "healthy", "service_url": SERVICE_URL})


if __name__ == '__main__':
    # 从环境变量获取主机和端口，如果没有则使用默认值
    host = os.environ.get('PROBE_HOST', '0.0.0.0')
    port = int(os.environ.get('PROBE_PORT', 8000))
    
    app.run(host=host, port=port, debug=True)